package space.panker916.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import space.panker916.dao.UserMapper;
import space.panker916.pojo.LoginTicket;
import space.panker916.pojo.User;
import space.panker916.utils.CommunityUtil;
import space.panker916.utils.MailClient;
import space.panker916.utils.RedisKeyUtil;

import javax.mail.MessagingException;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static space.panker916.utils.Constants.*;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

//    @Autowired
//    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    public User findUserById(int id) {
        User user = getCacheUserById(id);                   // 缓存中有值的话直接取
        if (user == null) user = initCacheUserById(id);      // 缓存中没值的话初始化
        return user;
    }

    public Map<String, Object> register(User user) throws MessagingException {
        Map<String, Object> map = new HashMap<>();

        // 对传入的对象做一些判断
        if (user == null) throw new IllegalArgumentException("传进来的用户对象不能为空");

        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "用户名不能为空");
            return map;
        }

        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空");
            return map;
        }

        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空");
            return map;
        }

        User user1 = userMapper.selectByName(user.getUsername());
        if (user1 != null) {
            map.put("usernameMsg", "该用户名已经被注册");
            return map;
        }

        User user2 = userMapper.selectByEmail(user.getEmail());
        if (user2 != null) {
            map.put("emailMsg", "该邮箱已经被注册");
            return map;
        }

        // 注册用户（加密用户密码（使用原密码 + 随机字符串 然后 通过 md5 加密））
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.MD5(user.getPassword() + user.getSalt()));
        user.setType(0);            // 普通用户
        user.setStatus(0);          // 未激活（邮箱未验证）
        user.setActivationCode(CommunityUtil.generateUUID());       // 生成 邮箱 验证码
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));    // 生成随机头像
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        // 发送激活邮件
        Context context = new Context();
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("email", user.getEmail());
        context.setVariable("url", url);
        String text = templateEngine.process("/mail/activation", context);

        mailClient.sendMail(user.getEmail(), "激活账号", text);

        return map;
    }

    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getActivationCode().equals(code)) {
            if (user.getStatus() == 1) return ACTIVATION_REPEAT;             // 代表重复激活
            else {
                userMapper.updateStatus(userId, 1);
                clearCacheUserById(userId);
                return ACTIVATION_SUCCESS;
            }
        } else return ACTIVATION_FAILURE;
    }

    public Map<String, Object> login(String username, String password, long expireSeconds) {
        Map<String, Object> map = new HashMap<>();

        // 空值的处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空！");
            return map;
        }

        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }

        // 对合法性进行验证
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在！");
            return map;
        }

        // 验证账号是否激活
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活！");
            return map;
        }

        // 验证密码
        password = CommunityUtil.MD5(password + user.getSalt());

        // 密码不正确
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确！");
            return map;
        }

        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expireSeconds * 1000));
        redisTemplate.opsForValue().set(RedisKeyUtil.getTicketKey(loginTicket.getTicket()), loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    // 不是真的退出，而是把 ticket 的状态改成 1
    public void logout(String ticket) {
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(ticketKey, loginTicket);
    }


    public LoginTicket findLoginTicket(String ticket) {
        return (LoginTicket) redisTemplate.opsForValue().get(RedisKeyUtil.getTicketKey(ticket));
    }

    public User findUserByName(String username) {
        return userMapper.selectByName(username);
    }

    public int updateHeader(int userId, String headerUrl) {
        int rows = userMapper.updateHeader(userId, headerUrl);
        clearCacheUserById(userId);
        return rows;
    }

    public int updatePassword(int userId, String password) {
        int rows = userMapper.updatePassword(userId, password);
        clearCacheUserById(userId);
        return rows;
    }

    // 1. 当查询时，优先从缓存中取值
    private User getCacheUserById(int userId) {
        return (User) redisTemplate.opsForValue().get(RedisKeyUtil.getUserKey(userId));
    }

    // 2. 取不到时，就初始化缓存数据
    private User initCacheUserById(int userId) {
        User user = userMapper.selectById(userId);
        redisTemplate.opsForValue().set(RedisKeyUtil.getUserKey(userId), user, 60 * 60, TimeUnit.SECONDS);
        return user;
    }

    // 3. 数据变更时要清除缓存数据（下次再使用时重新加载）
    // 先进行数据变更，然后再清理缓存。因为 redis 和 MySQL 的事务不一致，这样如果数据变更失败，缓存就不会被清理掉了
    private void clearCacheUserById(int userId) {
        redisTemplate.delete(RedisKeyUtil.getUserKey(userId));
    }

    public Collection<? extends GrantedAuthority> getAuthority(int userStatus) {
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            private static final long serialVersionUID = 500251069238872397L;

            @Override
            public String getAuthority() {
                if (userStatus == 0) return AUTHORITY_USER;
                else if (userStatus == 1) return AUTHORITY_ADMIN;
                else return AUTHORITY_MODERATOR;
            }
        });

        return list;
    }
}
